<template>
  <div class="table-board-container">
    <div class="table-header">
      <h2>{{ t('header.tableBoard') }}</h2>
      <div class="table-actions">
        <el-input
          v-model="searchKeyword"
          :placeholder="t('homepage.searchPlaceholder')"
          prefix-icon="Search"
          clearable
          @clear="handleSearch"
          @input="handleSearchInput"
        />
        <el-button type="primary" @click="createNewCard">
          <el-icon><Plus /></el-icon>
          {{ t('homepage.createCard') }}
        </el-button>
      </div>
    </div>

    <!-- 批量删除操作栏 -->
    <div class="batch-actions" v-if="multipleSelection.length > 0">
      <span class="selection-info">
        {{ t('common.selected') }}: {{ multipleSelection.length }} {{ t('common.items') }}
      </span>
      <div class="batch-buttons">
        <el-button type="primary" size="small" @click="selectAllItems">
          {{ t('common.selectAll') }}
        </el-button>
        <el-button size="small" @click="clearSelection">
          {{ t('common.unselectAll') }}
        </el-button>
        <el-button type="danger" size="small" @click="batchDelete">
          {{ t('common.batchDelete') }}
        </el-button>
      </div>
    </div>

    <div class="table-content">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        height="100%"
        style="width: 100%"
        row-key="id"
        @row-click="handleRowClick"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
      >
        <!-- 添加多选列 -->
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="(row: CardItem) => true"
          @click.stop
        />
        
        <el-table-column 
          type="index" 
          label="序号" 
          width="60" 
          align="center"
          :index="indexMethod"
        />
        
        <el-table-column 
          prop="title" 
          :label="t('table.title')" 
          min-width="200"
          sortable="custom"
        >
          <template #default="{ row }">
            <div class="title-cell">
              <span>{{ row.title || t('cardEditor.untitledDoc') }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 添加桶名称列 -->
        <el-table-column 
          prop="bucket" 
          :label="t('table.bucket')" 
          min-width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <div class="bucket-cell">
              <span>{{ row.bucket || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="tags" 
          :label="t('table.tags')" 
          min-width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            <div class="tags-cell">
              <el-tag 
                v-for="tag in row.tags" 
                :key="tag" 
                size="small" 
                class="tag-item"
                :style="row.tagColors && row.tagColors[tag] ? 
                  {backgroundColor: row.tagColors[tag] + '33', borderColor: row.tagColors[tag], color: row.tagColors[tag]} : 
                  {}"
              >
                {{ tag }}
              </el-tag>
              <span v-if="!row.tags || row.tags.length === 0">-</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column 
          prop="startTime" 
          :label="t('table.startTime')" 
          min-width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ formatTimeFieldSync(row.startTime, 'start') || '-' }}
          </template>
        </el-table-column>

        <el-table-column 
          prop="created" 
          :label="t('table.createdAt')" 
          min-width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ formatTimeFieldSync(row.created, 'created') }}
          </template>
        </el-table-column>

        <el-table-column 
          prop="updated" 
          :label="t('table.updatedAt')" 
          min-width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ formatTimeFieldSync(row.updated, 'updated') }}
          </template>
        </el-table-column>

        <el-table-column :label="t('table.actions')" width="150" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click.stop="editCard(row)">
                {{ t('common.edit') }}
              </el-button>
              <el-button size="small" type="danger" @click.stop="deleteCard(row)">
                {{ t('common.delete') }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="empty-data" v-if="!loading && tableData.length === 0">
        <el-empty :description="t('table.noData')" />
      </div>
    </div>

    <div class="pagination-container" v-if="tableData.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizeOptions"
        :layout="paginationLayout"
        :total="total"
        :total-text="t('table.total', { total: total })"
        :page-size-label="t('table.itemsPerPage')"
        :goto-label="t('table.gotoPage')"
        :page-label="t('table.page')"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { format } from 'date-fns';
import { zhCN, enUS } from 'date-fns/locale';
import { fetchCards, deleteCard as deleteCardApi } from '../services/cardService';
import type { CardItem } from '../types/cardData';
import { setSourcePage } from '../utils/navigation';
import { formatDateTimeSync, formatTimeFieldSync } from '../utils/dateFormatter';

const { t, locale } = useI18n();
const router = useRouter();

// 从设置中获取页面大小选项
const getPageSizeOptions = (): number[] => {
  try {
    const generalSettings = localStorage.getItem('general-settings');
    if (generalSettings) {
      const settings = JSON.parse(generalSettings);
      if (settings.pageSizeOptions && Array.isArray(settings.pageSizeOptions) && settings.pageSizeOptions.length > 0) {
        return settings.pageSizeOptions;
      }
    }
  } catch (error) {
    console.error('获取页面大小选项设置失败:', error);
  }
  return [10, 20, 50, 100]; // 默认值
};

// 从设置中获取默认页面大小
const getDefaultPageSize = (): number => {
  try {
    const generalSettings = localStorage.getItem('general-settings');
    if (generalSettings) {
      const settings = JSON.parse(generalSettings);
      if (settings.pageSize && typeof settings.pageSize === 'number') {
        return settings.pageSize;
      }
    }
  } catch (error) {
    console.error('获取默认页面大小设置失败:', error);
  }
  return 20; // 默认值
};

// 表格数据
const tableData = ref<CardItem[]>([]);
const loading = ref(false);
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(getDefaultPageSize());
const pageSizeOptions = ref(getPageSizeOptions());
const total = ref(0);
const allCards = ref<CardItem[]>([]);

// 排序相关
const sortBy = ref('');
const sortOrder = ref('');

// 分页布局
const paginationLayout = 'total, sizes, prev, pager, next, jumper';

// 加载卡片数据
const loadCards = async () => {
  loading.value = true;
  try {
    // 从服务获取所有卡片
    const response = await fetchCards(1, 1000); // 获取所有卡片，后续在客户端分页
    allCards.value = response.items;
    total.value = response.total;
    
    // 搜索过滤
    let filteredCards = allCards.value;
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase();
      filteredCards = allCards.value.filter((card) => 
        card.title?.toLowerCase().includes(keyword) || 
        card.content?.toLowerCase().includes(keyword) ||
        card.tags?.some((tag) => tag.toLowerCase().includes(keyword))
      );
    }
    
    // 应用排序
    if (sortBy.value && sortOrder.value) {
      filteredCards = sortCards(filteredCards, sortBy.value, sortOrder.value);
    }
    
    // 分页处理
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    tableData.value = filteredCards.slice(start, end);
  } catch (error) {
    console.error('Failed to load cards:', error);
    ElMessage.error(t('table.loadError'));
  } finally {
    loading.value = false;
  }
};

// 处理表格排序变化
const handleSortChange = (column: { prop: string, order: string }) => {
  sortBy.value = column.prop;
  // Element Plus的排序顺序是ascending和descending
  sortOrder.value = column.order === 'ascending' ? 'asc' : column.order === 'descending' ? 'desc' : '';
  loadCards();
};

// 排序卡片函数
const sortCards = (cards: CardItem[], sortBy: string, sortOrder: string) => {
  const compareFn = (a: CardItem, b: CardItem) => {
    let valueA: any, valueB: any;
    
    // 特殊处理tags字段，因为它是数组
    if (sortBy === 'tags') {
      valueA = a.tags && a.tags.length > 0 ? a.tags[0] : '';
      valueB = b.tags && b.tags.length > 0 ? b.tags[0] : '';
    } else {
      valueA = a[sortBy as keyof CardItem] || '';
      valueB = b[sortBy as keyof CardItem] || '';
    }
    
    // 时间类型值特殊处理
    if (sortBy === 'startTime' || sortBy === 'created' || sortBy === 'updated') {
      valueA = typeof valueA === 'string' ? new Date(valueA).getTime() : 0;
      valueB = typeof valueB === 'string' ? new Date(valueB).getTime() : 0;
    }
    
    // 字符串特殊处理
    if (typeof valueA === 'string' && typeof valueB === 'string') {
      return sortOrder === 'asc' 
        ? valueA.localeCompare(valueB) 
        : valueB.localeCompare(valueA);
    }
    
    // 数字类型比较
    return sortOrder === 'asc' ? (valueA > valueB ? 1 : -1) : (valueA < valueB ? 1 : -1);
  };
  
  return [...cards].sort(compareFn);
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadCards();
};

// 处理搜索输入，添加防抖处理
let searchTimeout: number | null = null;
const handleSearchInput = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout);
  }
  searchTimeout = window.setTimeout(() => {
    handleSearch();
  }, 300);
};

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadCards();
};

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadCards();
};

// 创建新卡片
const createNewCard = () => {
  router.push({ name: 'CardEditor' });
};

// 编辑卡片
const editCard = (card: CardItem) => {
  router.push({ name: 'EditCard', params: { id: card.id } });
};

// 查看卡片详情
const handleRowClick = (row: CardItem, column: any, event: MouseEvent) => {
  // 如果点击的是复选框或复选框所在的列，不进行跳转
  const isCheckboxColumn = column.type === 'selection';
  const isCheckboxClick = (event.target as HTMLElement).closest('.el-checkbox');
  
  if (isCheckboxColumn || isCheckboxClick) {
    return;
  }
  
  router.push({ name: 'ViewCard', params: { id: row.id } });
};

// 删除卡片
const deleteCard = (card: CardItem) => {
  ElMessageBox.confirm(
    t('viewCard.deleteConfirm'),
    t('common.confirm'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 使用API删除卡片
      const success = await deleteCardApi(card.id);
      
      if (success) {
        ElMessage.success(t('viewCard.deleteSuccess'));
        loadCards(); // 重新加载数据
      } else {
        ElMessage.error(t('viewCard.deleteFailed'));
      }
    } catch (error) {
      console.error('Failed to delete card:', error);
      ElMessage.error(t('viewCard.deleteFailed'));
    }
  }).catch(() => {
    // 用户取消删除操作
  });
};

// 计算行号的方法
const indexMethod = (index: number) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};

// 处理表格选择变化
const multipleSelection = ref<CardItem[]>([]);
const multipleTable = ref<any>(null);
const handleSelectionChange = (selection: CardItem[]) => {
  multipleSelection.value = selection;
};

// 批量删除操作
const batchDelete = () => {
  if (multipleSelection.value.length === 0) {
    return;
  }
  
  ElMessageBox.confirm(
    t('viewCard.batchDeleteConfirm', { count: multipleSelection.value.length }),
    t('common.confirm'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true;
    try {
      // 获取所有选中卡片的ID
      const cardIds = multipleSelection.value.map(card => card.id);
      
      // 调用批量删除API
      const result = await import('../services/cardService').then(module => {
        return module.batchDeleteCards(cardIds);
      });
      
      if (result.success) {
        ElMessage.success(t('viewCard.batchDeleteSuccess', { count: result.count }));
        // 重新加载数据
        loadCards();
        // 清除选择
        clearSelection();
      } else {
        ElMessage.error(t('viewCard.batchDeleteFailed'));
      }
    } catch (error) {
      console.error('Failed to batch delete cards:', error);
      ElMessage.error(t('viewCard.batchDeleteFailed'));
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 用户取消删除操作
  });
};

// 选择所有表格项
const selectAllItems = () => {
  if (multipleTable.value) {
    multipleTable.value.toggleAllSelection();
  }
};

// 清除表格选择
const clearSelection = () => {
  if (multipleTable.value) {
    multipleTable.value.clearSelection();
  }
};

// 检查设置是否变化
const checkForSettingsChanges = () => {
  // 检查页面大小设置是否变化
  const newPageSize = getDefaultPageSize();
  const newPageSizeOptions = getPageSizeOptions();
  
  let needReload = false;
  
  // 检查页面大小是否变化
  if (newPageSize !== pageSize.value) {
    console.log('检测到页面大小设置变化:', pageSize.value, '->', newPageSize);
    pageSize.value = newPageSize;
    needReload = true;
  }
  
  // 检查页面大小选项是否变化
  if (JSON.stringify(newPageSizeOptions) !== JSON.stringify(pageSizeOptions.value)) {
    console.log('检测到页面大小选项设置变化');
    pageSizeOptions.value = newPageSizeOptions;
  }
  
  // 如果页面大小变化且已加载数据，重新加载
  if (needReload && tableData.value.length > 0) {
    loadCards();
  }
};

// 组件挂载时
onMounted(() => {
  // 设置当前页面为导航来源
  setSourcePage('TableBoard');
  
  // 加载卡片数据
  loadCards();
  
  // 监听窗口焦点变化，以便在设置改变时更新
  window.addEventListener('focus', checkForSettingsChanges);
});

// 组件卸载时
onBeforeUnmount(() => {
  // 移除窗口焦点事件监听
  window.removeEventListener('focus', checkForSettingsChanges);
});
</script>

<style scoped>
.table-board-container {
  height: calc(100vh - 48px);
  display: flex;
  flex-direction: column;
  padding: 16px;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 0;
}

.table-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 12px;
}

.table-content {
  flex: 1;
  overflow: hidden;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.tags-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag-item {
  margin-right: 4px;
}

.title-cell {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  padding: 8px 0;
}

.empty-data {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.batch-actions {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.08);
}

.selection-info {
  margin-right: 10px;
  color: #606266;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

/* 增加响应式适配 */
@media screen and (max-width: 768px) {
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .table-actions {
    width: 100%;
  }
  
  .table-actions .el-input {
    width: 100%;
  }
}
</style> 